<template>
  <div>
    <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" drag :auto-upload="false"
      :on-change="handelChange">
      <!-- 插槽父组件中传入，传过来的内容最好有div容器包裹 -->
      <slot></slot>
    </el-upload>
  </div>
</template>

<script>
  // import cos form "cos-js-sdk-v5"
  var Buckets = "lumayun-1305480448";
  var Regions = "ap-guangzhou";
  var protocol = location.protocol === "https:" ? "https:" : "http:";
  var prefix = protocol + "//" + Buckets + ".cos." + Regions + ".myqcloud.com";
  var camSafeUrlEncode = function (str) {
    return encodeURIComponent(str)
      .replace(/!/g, "%21")
      .replace(/'/g, "%27")
      .replace(/\(/g, "%28")
      .replace(/\)/g, "%29")
      .replace(/\*/g, "%2A");
  };
  let obj = {
    file_name: "",
    key: ""
  };
  export default {
    props: {
      type: [String, Number],
      module: String,
      progress: Function,
      beforeupload: Function, //开始上传前调用
      change: Function, //文件开始上传调用
      success: Function, //文件上传成功调用
      error: Function,
      rzstatus: [String, Number], //该参数用来验证是否实名制

    },
    data() {
      return {
        imageUrl: "",
        info: {
          myparams: {},
          XCosSecurityToken: ""
        },
        upimgBase64: '',
        ismobileconfig: false
      };
    },
    methods: {
      // 选中文件
      handelChange(file) {
        let that = this;
        let data = file;
        if (this.beforeupload(file)) {
          this.getAuthorization(file);
        }
      },
      // 获得上传临时密钥
      getAuthorization(file) {
        var params = new FormData();
        params.append("type", this.type);
        params.append("module", this.module);
        this.$post(
          "https://api.lumayun.com/api/Qcloudclient/getTempKeysV2",
          params
        ).then(res => {
          if (res) {
            console.log(res);
            obj.file_name = res.file_name;
            obj.key = res.key;
            var Key = `${obj.key}${obj.file_name}`; // 这里指定上传目录和文件名
            var credentials;
            try {
              credentials = res.credentials;
            } catch (e) {
              // console.log(e);
            }
            if (credentials) {
              var XCosSecurityToken = credentials.sessionToken;
              var Authorization = CosAuth({
                SecretId: credentials.tmpSecretId,
                SecretKey: credentials.tmpSecretKey,
                Method: "PUT",
                Pathname: "/" + Key
              });
              console.log(file);
              var info = {
                XCosSecurityToken,
                Authorization,
                Key,
                file
              };
              // console.log(XCosSecurityToken + "-----" + Authorization);
              if (this.type != 1) {
                this.change(file);
              }
              this.uploadFile(info, false);
            } else {
              callback("获取签名出错");
            }
          }
        });
      },
      // 开始上传文件
      uploadFile(info, boolean) {
        // console.log(info);
        let that = this;
        var auth = info.Authorization;
        var XCosSecurityToken = info.XCosSecurityToken;
        var url = prefix + "/" + camSafeUrlEncode(info.Key).replace(/%2F/g, "/");
        // 这个地方不能使用formData,PutObject 接口上传的 Body 不是 FormData，是文件（File对象/Blob对象/字符串/ArrayBuffer）本身
        // var params = new FormData();
        var file;
        if (this.type == 1) {
          file = info.file;
        } else {
          file = info.file.raw;
        }
        var reader = new FileReader();
        reader.readAsArrayBuffer(file.raw);
        reader.onload = function (e) {
          this.result // 这个就是base64编码了
          console.log(this.result);
          // params.append("file",file );
          const config = {
            onUploadProgress: that.progress
          };
          that.$put(url, this.result, {
            auth,
            XCosSecurityToken
          }, config).then(() => {
            console.log(url);
            that.success(url);
          });
        }
      }
    }
  };

</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  div>>>.el-upload-dragger {
    width: auto;
    height: auto;
  }

  div>>>.el-upload-list__item-name {
    display: none;
  }

</style>
